<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Shine课程表活动-2021，你想做什么</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/popper.js/1.15.0/popper.min.js" type="module"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
    <link rel="stylesheet" href="../static/styles/what_to_do_2021.css" th:href="@{/styles/what_to_do_2021.css}"/>
</head>
<body>
    <div class="root">
        <div class="top_bar" th:include="top"></div>

        <div class="container-fluid">
            <div class="row">
                <!--弹幕容器-->
                <div class="col-sm-12 danmu_container">
                </div>
            </div>

            <div class="row fixed-bottom">
                <div class="col-sm-12">
                    <div class="row">
                        <div class="col-sm-12">
                            <span id="online-count" style="background-color: rgba(0,0,0,0.5);color: white"></span>
                        </div>
                    </div>

                    <div class="row" style="height: 100px;">
                        <div class="col-sm-10">
                            <input class="input-view form-control" id="input-content" name="content" type="text" placeholder="写下你的2021年愿望吧" style="width: 100%;height: 100%">
                        </div>
                        <div class="col-sm-2">
                            <button type="button" class="btn btn-success" onclick="biu()" style="width: 100%;height: 100%">
                                发送
                            </button>
                        </div>
                        <div class="col-sm-1"></div>
                    </div>

                    <!--页脚-->
                    <div th:include="footer"></div>
                </div>
            </div>
        </div>

    </div>
</body>
<script type="text/javascript" th:inline="javascript">
    window.onload = function () {
        initStyle();
        initDanmu();
    };

    function initStyle() {
        const navbar = document.getElementsByClassName('navbar')[0];
        const brand = document.getElementsByClassName('navbar-brand')[0];
        const text = document.getElementsByClassName('nav-link');
        const icon = document.getElementsByClassName('navbar-toggler-icon')[0];
        navbar.style.background = 'linear-gradient(90deg, rgb(230, 254, 229) 0%, rgb(220, 231, 255) 100%)';
        brand.style.color = 'rgba(0, 0, 0, 1)';
        for (let i = 0; i<text.length; i++) {
            text[i].style.color = 'rgba(0, 0, 0, 1)';
        }
        icon.style.backgroundImage = 'url("data:image/svg+xml,%3csvg viewBox=\'0 0 30 30\' xmlns=\'http://www.w3.org/2000/svg\'%3e%3cpath stroke=\'rgba(' + 0 + ',' + 0 + ',' + 0 + ', 1)\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-miterlimit=\'10\' d=\'M4 7h22M4 15h22M4 23h22\'/%3e%3c/svg%3e")'
    }

    //setInterval函数的返回值，用来关闭方法
    let intervarCount2;

    //由窗口高度决定弹幕可以显示位置的最低高度， 75 top 200 bottom 150 other
    let maxHeight = Math.max($(document).height() - 75 - 200 - 150, 0);
    $(window).resize(function () {
        maxHeight = Math.max($(document).height() - 75 - 200 - 150, 0);
    });

    //想要做列表
    const whatToDoList = [[${what_to_do_list}]];

    const noticeList = [
        '2021年就要到了，看看大家的心愿吧',
        '前方即将到达心愿弹幕，请注意查收',
        '新的一年大家都有什么愿望呢',
        '2021年就要到了，看看大家的心愿吧',
        '前方即将到达心愿弹幕，请注意查收',
        '新的一年大家都有什么愿望呢'];

    //对当前为第几条弹幕做记录
    let i = 0;
    let j = 0;

    function initDanmu() {
        initNoticeDanmu();

        //只有列表不为空，才去执行
        if (whatToDoList.length > 0) {
            //每隔1.5秒发射一条弹幕
            window.setInterval("addDanmu(whatToDoList[i])", 1500);
        }
    }

    //初始化提醒弹幕
    function initNoticeDanmu() {
        intervarCount2 = window.setInterval('addNoticeDanmu(noticeList[j])', 250)
    }

    function addNoticeDanmu(text) {
        const content = $("<div class='danmu'>" + text + "</div>");

        //固定在此范围内显示
        const top = 75 + Math.abs(Math.round(Math.random() * maxHeight)) + "px";
        content.css("top", top);

        //随机背景颜色
        const R = Math.round(Math.random() * 255);
        const G = Math.round(Math.random() * 255);
        const B = Math.round(Math.random() * 255);
        content.css('background-color', 'rgba(' + R + ',' + G + ',' + B + ',0.5)');

        content.css('font-size', '35px');
        content.css('right', '-600px');

        $(".danmu_container").append(content);

        content.animate({right: $(document.body).width() + 400}, 8000, 'linear' ,function () {
            $(this).remove();
        });

        //循环一遍即停止
        j++;
        if (j >= noticeList.length) {
            clearInterval(intervarCount2);
        }
    }

    function addDanmu(whatToDo) {
        const content = $("<div class='danmu'>" + whatToDo.content + "</div>");

        //如果说这条弹幕是自己发送的，那么加一个描边
        if (whatToDo.userId == [[${userIdDB}]]) {
            content.css('border', '3px rgb(217,217,25) solid')
        }

        addToContainer(content, whatToDo.content);
        i = Math.abs(Math.round(Math.random()*whatToDoList.length-1));
    }

    function addToContainer(content, text) {
        //固定在此范围内显示
        const top = 75 + Math.abs(Math.round(Math.random() * maxHeight)) + "px";
        content.css("top", top);

        //随机背景颜色
        const R = Math.round(Math.random() * 255);
        const G = Math.round(Math.random() * 255);
        const B = Math.round(Math.random() * 255);
        content.css('background-color', 'rgba(' + R + ',' + G + ',' + B + ',0.5)');

        //随机字体大小
        const fontSize = Math.round(15 + Math.abs(Math.random()) * 25);
        content.css('font-size', fontSize + 'px');

        //弹幕的出现和结束位置，这个字越大，字越多，就应该向右（左）移动越多
        const danmuPosition = Math.max(fontSize * text.length, 125);

        $(".danmu_container").append(content);

        //先把弹幕div添加到控件中获取宽度，然后获取列表最后一个，就是最后添加进来的，就是最新的div，然后把这个宽度设置给它，就可以完美了
        const danmuClassList = document.getElementsByClassName('danmu');
        content.css('right', danmuClassList[danmuClassList.length - 1].offsetWidth * -1 + 'px');

        //jquery实现的动画，根据字长确定速度，注意，这个数字越大，就越慢，但是随机数可能导致过小，所以加上一个取大值的限制
        const speed = Math.max((17500 - text.length * fontSize * 100 * Math.abs(Math.random())), text.length * fontSize * 50);
        content.animate({right: $(document.body).width() + danmuPosition * 4}, speed, 'linear' ,function () {
            $(this).remove();
        });
    }

    //发送弹幕，存储到数据库，同时显示在网页上
    function biu() {
        //val()获取值
        const text = $('#input-content').val();

        if (text.length <= 0) {
            Swal.fire('错误', '您的愿望好像是空的', 'error');
        } else {
            $.ajax({
                type: 'POST',
                url: '/send_danmu',
                dataType:'json',
                data: {content: text},
                success: function (result) {
                    if (result.resultCode == 501) {
                        Swal.fire('错误','只有登录后你的愿望才会存储和被他人看到噢', 'error')
                    } else if (result.resultCode == 500) {
                        Swal.fire({
                            title: '错误',
                            text: '发送太频繁啦，稍后再试吧',
                            type: 'error',
                            showConfirmButton: false
                        })
                    }
                },
                error: function () {
                    Swal.fire('存储失败', {
                        icon: 'error'
                    })
                }
            })
        }
    }

    //监听回车
    document.onkeydown = function enter(e) {
        const ev = document.all ? window.event : e;
        if(ev.keyCode==13) {
            biu()
        }
    };

    let websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://"+document.location.host+"/webSocket");
    }

    websocket.onopen = function(){
        console.log("连接成功");
    };

    websocket.onclose = function(){
        console.log("退出连接");
    };

    websocket.onmessage = function (event){
        //JSON字符串转对象才可操作
        const myMessage = jQuery.parseJSON(event.data);
        //系统消息
        if (myMessage.myType == 0) {
            document.getElementById('online-count').innerText = myMessage.myMessage;
        }
        //弹幕消息
        else if (myMessage.myType == 1) {
            const content = $("<div class='danmu'>" + myMessage.myMessage + "</div>");

            //实时弹幕
            content.css('border', '3px red solid');

            addToContainer(content, myMessage.myMessage);

            console.log('收到消息：' + myMessage.myMessage);
        }

    };

    websocket.onerror = function(){
        console.log("连接出错");
    };

    window.onbeforeunload = function () {
        websocket.close(num);
    };
</script>
</html>